# Get latest wallpaper from web and set it as desktop wallpaper.
# Todo:
# 1. Support more(better) picture websites
#!/usr/bin/env python
from debugger import *
from wallpaper_modules import *
from misc import win_quote1, win_quote2
import configs

import sys
import os
import random
import subprocess
import popen2

DEFAULT_MODULE = 3

# Set as wallpaper
def setwallpaper(filepath):
    #import ctypes
    #from win32con import SPI_SETDESKWALLPAPER
    #ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, outputfile , 0)

    #import _winreg as wreg
    #key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, wreg.KEY_ALL_ACCESS)
    #v = wreg.QueryValueEx(key, "WallPaper")
    #print "Key value is : ", v
    #wreg.SetValue(key, "WallPaper", wreg.REG_SZ, outputfile)
    if filepath:
        bmpfile = os.path.join(configs.Configs["OUTPUT_PATH"], "wallpaper.bmp")
        cmd1 = "%s %s /convert=%s" % (win_quote1(configs.Configs["IRFANVIEW_FILE"]), win_quote2(filepath), win_quote2(bmpfile))
        cmd2 = "%s /D:S %s" % (win_quote1(os.path.join(configs.Configs["SETWALLPAPER_PATH"], "setwallpaper")), win_quote2(bmpfile))
        DEBUG.p("cmd1: %s" % cmd1)
        DEBUG.p("cmd2: %s" % cmd2)

        subprocess.Popen(cmd1).wait()

        # Can't work: no stdout rediection
        #os.system(cmd2)

        # Can't work in no console mode?
        #p = subprocess.Popen(cmd2,stdout=subprocess.PIPE)
        #output = p.commmunicat()[0]
        #output += "."
        #p.wait()

        #stdin, stdout = popen2.popen2(cmd2)
        #stdin.close()
        #stdout.close()
    else:
        print "Invalid wallpaper path: %s" % filepath

def print_help():
    print "Usage:"
    print "%s [options] index" % (sys.argv[0])
    print "\tindex:\t\tThe index of module to run"
    print "Options:"
    print "\t-d:\t\tEnable debug mode"
    print "\t-l:\t\tList all modules"
    print "\t-r:\t\tRun random modules"

if __name__ == '__main__':
    # Import Psyco if available
    try:
        import psyco
        psyco.full()
    except ImportError:
        pass

    random.seed()

    wallpaper_modules = WallPaperModules()

    index = -1

    for arg in sys.argv[1:]:
        if arg == "-d":
            DEBUG.enable()
        elif arg == "-l":
            wallpaper_modules.list_modules()
            sys.exit(0)
        elif arg == "-h" or arg == "-?" or arg == "/?" or arg == "--help":
            print_help()
            sys.exit(0)
        elif arg == "-r":
            index = random.randint(1, wallpaper_modules.num_of_modules())
        elif arg[0] != "-":
            index = int(arg)

    configs.parse_configs()
    DEBUG.p("Config is:\n%s" % configs.Configs)

    #if index == 0:
    #    setwallpaper("C:\\Documents and Settings\\qhe\\My Documents\\My Pictures\\InLIFT_00663_ghostfog.jpg")
    #else:
    #    setwallpaper("C:\\Devel\\svnsrc\\python\\webwallpaper\\dist\\wallpapers\\InLIFT_00397_venice.jpg")
    #sys.exit(0)

    if index == -1:
        index = DEFAULT_MODULE

    DEBUG.p("Module index is %d" % index)

    if index > wallpaper_modules.num_of_modules():
        print "Module index out of range. Please select between 1 - %d" % (wallpaper_modules.num_of_modules())
    else:
        setwallpaper(wallpaper_modules.run_module(index))